package control;

import java.sql.ResultSet;
import java.sql.SQLException;

import db.DBConnecter;

public class TransferControl {
	private DBConnecter db;
	public TransferControl() {
		db = new DBConnecter();//initialize a new connection
	}//directly use DAO level 
	//use java transaction
	public String transferMoney(String sourceId, String targetId, String money,String note,String time,String sourcePassword){
		float moneyAmount = Float.parseFloat(money);
		
		String sourceSql = "update account set acc_credit = acc_credit - "+moneyAmount+" where acc_id = '"+sourceId+"'";
		String targetSql = "update account set acc_credit = acc_credit + "+moneyAmount+" where acc_id = '"+targetId+"'";
		String transactionSql = "insert into transaction(tx_amount, tx_from_account_id, tx_to_account_id, tx_datetime, tx_note) values("+moneyAmount+",'"+sourceId+"','"+targetId+"','"+time+"','"+note+"')";
		//System.out.println("doing the transfer.......just got" +sourceId +" " + targetId +" "+ money+" " + note+" " + time);
		
		//first check the password and the target account
		String checkPasswrodSql = "select acc_password from account where acc_id = '"+sourceId+"'";
		try{
			ResultSet rs0 = db.query(checkPasswrodSql);
			rs0.next();
			if(rs0.getString("acc_password").equals(sourcePassword)){
				
			}else{
				return "wrong account password";
			}
			
		}catch(SQLException e2){
			e2.printStackTrace();
			return "check password error";
		}
		
		String checkTargetAccountSql = "select count(*) from account where acc_id = '"+targetId+"'";
		try{
			ResultSet rs1 = db.query(checkTargetAccountSql);
			rs1.next();
			if(rs1.getInt(1) >= 1){
				
			}else{
				return "target account doesn't exist";
			}
		}catch(SQLException e3){
			e3.printStackTrace();
			return "check target account exists error";
		}
		
		try{
			db.getConn().setAutoCommit(false);
			db.getStmt().executeUpdate(sourceSql);
			db.getStmt().executeUpdate(targetSql);
			db.getStmt().executeUpdate(transactionSql);
			db.getConn().commit();
			db.close();
			return "success";
		}catch(SQLException e){
			e.printStackTrace();
			try {
				db.getConn().rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				db.close();
				return "error";
			}
			db.close();
			return "error";
		}
		
	}
}
